<?php

namespace app\admin\controller\task;

use app\common\controller\Backend;
use think\Db;
/**
 * 订单管理
 *
 * @icon fa fa-circle-o
 */
class DeliverGoods extends Backend
{

    /**
     * Order模型对象
     * @var \app\admin\model\shop\Order
     */
    protected $model = null;

    /**
     * 快速搜索时执行查找的字段
     */
    protected $searchFields = 'order_id';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\shop\Order;
        $this->view->assign("orderStateList", $this->model->getOrderStateList());
        $this->view->assign("flagList", $this->model->getFlagList());
        $this->view->assign("roomList", $this->model->getRoomList());
        $this->view->assign("authorStatusList", $this->model->getAuthorStatusList());
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    /**
     * 查看
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {

                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $join[]    = ["user u", "u.uid = o.uid"];
            $join[]    = ["shop_task t", "t.task_id = o.task_id"];
            $join[]    = ['shop s', 's.shop_id = t.shop_id'];
            $join[]    = ['admin a', 'a.id = s.shop_admin_id'];
            $field     = "o.order_sno,o.real_money,o.order_id,o.uid,t.task_sno,t.task_type,s.shop_name,u.tao_bao_no,o.tao_bao_order_no,u.username,o.status,o.create_time,o.author_status,o.order_state,a.username as shop_username";
//            $condition = [
//                'o.status'      => 7,
//            ];
            if(session('admin')['athur_id']==1) {
                $condition['t.shop_admin_id'] = session('admin')['athor'];
            }else{
                $condition['t.shop_admin_id'] = session('admin')['id'];
            }
            $condition["o.status"] = array("egt",7);
            $condition["o.task_type"] = array("neq",3);
            $total  = $this->model->alias("o")->join($join)->field($field)->where($condition)->where($where)->count();
            $list   = $this->model->alias("o")->join($join)->field($field)->where($condition)->where($where)->limit($offset, $limit)->order("o.create_time desc")->select();
            foreach ($list as &$value) {
                $value['a.username'] = $value['shop_username'];
                $value['u.username'] = $value['username'];
                $value['o.status'] = $value['status'];
                $value['o.real_money'] = $value['real_money'];
                $value['o.create_time'] = $value['create_time'];
                $value['s.shop_name'] = $value['shop_name'];
            }
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 发货
     * @Author   chenjianghui
     * @DateTime 2018-09-11T19:30:20+0800
     * @return   [type]                   [description]
     */
    public function send($ids = '')
    {
        if ($this->request->isAjax()) {
            $params = $this->request->post('row/a');
            if (empty($params)) {
                $sendIds = $this->request->post('ids/a');
                foreach ($sendIds as $key => $value) {
                    $id[] = $value['order_id'];
                }
                unset($value);
            } else {
                $id = $params['ids'];
            }
            $row = $this->model->with("task")->where('order_id', 'in', $id)->where('status', 7)->select();

            if(count($row)==1 && $row[0]["order_state"]==1){
                return json(['code' => 0, 'msg' => '该订单已经撤销！']);
            }

            if (!$row) {
//                $this->error(__('No Results were found'));
                return json(['code' => 0, 'msg' => '未找到合适选项']);
            }
            try {

                $arr_id = [];//完成
                $arr_id_t = [];//改变状态9
                $user_arr = [];//已完成用户id
                $user_arr_finish = [];//未完成
                $order_list = [];//已完成订单列表
                $order_list_finished = [];//未完成
                foreach ($row as $key => $value) {
                    if($value["order_state"]!=1) {
                        if ($value["task"]->is_need_send == 1 && $value["task"]->is_good_evalute == 2 && $value["task"]->is_review == 2) {
                            $order_list[] = $value;
                            $arr_id[] = $value["order_id"];
                            $user_arr[] = $value["uid"];
                        } else {
                            $arr_id_t[] = $value["order_id"];
                            $order_list_finished[] = $value;
                            $user_arr_finish[] = $value["uid"];
                        }
                    }
                }
                if($arr_id>0){
                    $this->model->where('order_id', 'in', $arr_id)->update(['status' => 13,"update_time"=>time()]);
                    //改变用户的完成订单数
                    Db::name("user_attribute")->where("uid", "in",$user_arr)->setInc("task_finish_count", 1);
                }else{
                    return json(['code' => 0, 'msg' => '未找到合适选项']);
                }
                if($arr_id_t>0){
                    $this->model->where('order_id', 'in', $arr_id_t)->update(['status' => 9,"update_time"=>time()]);
                }
                //发送消息还有计算金额
                if($arr_id>0) {

                    $openid_list = Db::name("wx_users")->where("uid","in",$user_arr)->field("openid,uid")->select();
                    $openid_list_new = [];
                    foreach ($openid_list as $k=>$v){
                        $openid_list_new[$v["uid"]] = $v["openid"];
                    }
                    $user_name_list = Db::name("user")->where("uid","in", $user_arr)->field("username,uid")->select();
                    $user_name_list_new = [];
                    foreach ($user_name_list as $ko=>$vo){
                        $user_name_list_new[$vo["uid"]] = $vo["openid"];
                    }
                    foreach ($order_list as $key => $order_info) {
                            //发送短信模板订单完成
                            $uid = $order_info["uid"];
                            $content = [
                                $order_info["shop_name"], $order_info["goods_sno"], $order_info["real_money"], $user_name_list_new[$uid]
                            ];//推荐内容
                            $msg = [
                                "condition" => 14,
                                "touser" => $openid_list_new[$uid],
                                "content" => $content
                            ];
                            $MiniMsg = new  \app\common\lib\MiniMsg($msg);
                            $MiniMsg->sendMsg();//发送短信模板订单已完成
                            //计算钱
                            $gold = new \app\common\controller\GoldBean();
                            $gold->finishedBean($order_info);
                    }
                }

                if($arr_id_t>0){
                    $openid_list = Db::name("wx_users")->where("uid","in",$user_arr_finish)->field("openid,uid")->select();
                    $openid_list_new = [];
                    foreach ($openid_list as $k=>$v){
                        $openid_list_new[$v["uid"]] = $v["openid"];
                    }
                    $user_name_list = Db::name("user")->where("uid","in", $user_arr_finish)->field("username,uid")->select();
                    $user_name_list_new = [];
                    foreach ($user_name_list as $ko=>$vo){
                        $user_name_list_new[$vo["uid"]] = $vo["openid"];
                    }
                    foreach ($order_list_finished as $key => $order_info) {
                        //发送短信模板订单完成
                        $uid = $order_info["uid"];
                        $content = [
                            $order_info["order_sno"], date("Y-m-d H:i:s",$order_info["create_time"]), $order_info["real_money"], 1,"已发货"
                        ];//推荐内容
                        $msg = [
                            "condition" => 19,
                            "touser" => $openid_list_new[$uid],
                            "content" => $content
                        ];
                        $MiniMsg = new  \app\common\lib\MiniMsg($msg);
                        $MiniMsg->sendMsg();//发送短信模板订单已完成
                        //计算钱
//                        $gold = new \app\common\controller\GoldBean();
//                        $gold->finishedBean($order_info);
                    }

                }
                return json(['code' => 1, 'msg' => '发货成功']);
            } catch (Exception $e) {
                return json(['code' => 0, 'msg' => '发货失败']);
            }

        } else {
            return json(['code' => 0, 'msg' => '发货失败']);
        }
    }

}
